<?php

class Antz_Form_Component
{
    protected $classnames = array();
    protected $id = '';
    protected $isXhtml = false;
    protected $parameters = array();
    protected $required = false;
    protected $disabled = false;
    protected $showLabel = true;
    protected $wrap = true;
    protected $name = '';
    protected $value = '';
    protected $type = NULL;

    // because sometimes the components stored in a data member might need to access
    // 	the object that stores them (see Antz_Form_Components_Input::add('file'))...
    public $formObj = NULL;
    public $blockObj = NULL;
    public $fieldsetObj = NULL;

    public function required($bool=''){
        if($bool===true || $bool===false) $this->required = $bool;
        return $this;
    }

    public function getName(){
      return $this->name;
    }

    public function setId($id=''){
        if($id=='')$id = 'Antz_Form_Component'.rand();
        $this->id = $id;
        return $this;
    }

    public function addAftertext($text){
        $this->aftertext .= $text;
        return $this;
    }

    public function setWrap($bool){
        $this->wrap = (bool) $bool;
        return $this;
    }

    public function showLabel($bool){
        $this->showLabel = (bool) $bool;
        return $this;
    }

    public function getId(){
        return $this->id;
    }

    public function addParameter($name, $value){
        $this->parameters[] = array('name' => $name, 'value' => $value);
        return $this;
    }

    public function addAttribute($name, $value){
        $this->addParameter($name, $value);
        return $this;
    }

    public function addJsEvent($action, $function){
        return $this->addParameter($action, $function);
    }

    public function renderAttributes(){
        $returnString = '';
        foreach($this->parameters as $event){
            $returnString .= ' '.$event['name'].'="'.$event['value'].'" ';
        };
        return $returnString;
    }
    
    public function renderParameters(){
      return $this->renderAttributes();
    }

    public function isXhtml($param = ''){
        if($param === true || $param === false) $this->isXhtml = $param;
        return $this->isXhtml;
    }

    public function addClass($classname){
        $this->classnames[] = $classname;
        return $this;
    }

    public function renderClasses(){
        if(count($this->classnames)==0) return '';
        return ' class="'.implode(' ', $this->classnames).'" ';
    }

    public function disabled($bool){
        if($bool === true || $bool === false) $this->disabled = $bool;
        return $this;
    }

    protected function wrap($string){
        if($this->type == 'hidden') return $string;
        $isError = (Antz::isFormError($this->name)) ? ' error' : '';
        return '<div class="component'.$isError.' '.$this->type.'" id="'.$this->id.'_component">'.$string.'</div>';
    }

}
